import { defineStore } from 'pinia';

export const usePlantStore = defineStore('plant', {
  state: () => ({
    // 直接返回默认数据
    plants: [
      {
        id: 1,
        name: '绿萝',
        category: '观叶植物',
        stock: 20
      },
      {
        id: 2,
        name: '多肉',
        category: '多肉植物',
        stock: 30
      },
      {
        id: 3,
        name: '君子兰',
        category: '花卉植物',
        stock: 15
      }
    ]
  }),
  actions: {
    addPlant(plant) {
      const maxId = this.plants.reduce((max, p) => p.id > max ? p.id : max, 0);
      plant.id = maxId + 1;
      this.plants.push(plant);
      this.saveToLocalStorage();
    },
    updatePlant(updatedPlant) {
      const index = this.plants.findIndex(plant => plant.id === updatedPlant.id);
      if (index !== -1) {
        this.plants[index] = updatedPlant;
        this.saveToLocalStorage();
      }
    },
    deletePlant(id) {
      this.plants = this.plants.filter(plant => plant.id !== id);
      this.saveToLocalStorage();
    },
    saveToLocalStorage() {
      localStorage.setItem('plants', JSON.stringify(this.plants));
    }
  }
});
